package com.hnjd.headline.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnjd.headline.utils.Constant;
import com.hnjd.headline.utils.Result;
import com.hnjd.headline.utils.ResultCodeEnum;
import com.hnjd.headline.utils.TokenHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginProtectInterceptor implements HandlerInterceptor {

    @Autowired
    TokenHelper tokenHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constant.REQUEST_HEAD_TOKEN_KEY);

        if(token == null || token.isEmpty() || tokenHelper.isExpiration(token)) {
            // 响应504, 未登录
            Result result = Result.build(ResultCodeEnum.NOTLOGIN);
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);

            // 返回false, 拦截请求
            return false;
        }

        // 验证通过, 放行请求
        return true;
    }
}
